<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommonEnum;
use app\enum\OceanEnum;
use app\enum\OeCodeEnum;
use app\model\ClientAccountModel;
use app\model\CrontabTaskModel;
use app\model\OeMaterialDailyReportExtModel;
use app\model\OeMaterialDailyReportHistoryExtModel;
use app\model\OeMaterialDailyReportHistoryModel;
use app\model\OeMaterialDailyReportModel;
use app\model\OeVideoModel;
use app\service\client\AccountService;
use app\service\CrontabTaskService;
use app\service\ocean\FinanceService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Db;

class OeCustomMaterialDailyReportRecallWork extends BaseWork implements DailyStatWork
{
    public string $tag;

    public array $clientAccountInfo = [];

    /**
     * 设置任务标识.
     * @param mixed $tag
     */
    public function setTag($tag = ''): bool
    {
        if (! is_null($tag)) {
            $this->tag = strval($tag);
        }
        return true;
    }

    /**
     * 获取任务标识.
     */
    public function getTag(): string
    {
        return $this->tag;
    }

    /**
     * 获取脚本名.
     */
    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            //            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('oe_custom_material_daily_report_recall_work');
        $this->setDescription('巨量引擎-自定义素材日流水回溯');
        $this->addArgument('type', Argument::REQUIRED, '类型  1：主表 2：历史数据表');
        $this->addArgument('start_date', Argument::REQUIRED, '开始日期');
        $this->addArgument('end_date', Argument::REQUIRED, '结束日期');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $output->writeln('=======巨量引擎-自定义素材日流水拉取开始' . date('Y-m-d H:i:s', time()) . '=======');
        $type = intval($input->getArgument('type'));
        $startDate = $input->getArgument('start_date');
        $endDate = $input->getArgument('end_date');

        if (! $startDate || ! $endDate) {
            $output->writeln('===========开始时间，结束时间都必须存在！===========');
            return;
        }

        if ($startDate > $endDate) {
            $output->writeln('===========开始时间必须小于结束时间！===========');
            return;
        }
        $redis = Cache::store('redis')->handler();
        $redisKey = 'task:oe_video_cus_recall';
        for ($i = 0; $i < 100; ++$i) {
            $account = $redis->lPop($redisKey);
            if ($account) {
                $account = explode('_', $account);
                $advertiserId = $account[0];
                $execNum = intval($account[1]);
                $this->clientAccountInfo = $this->_getClientAccountInfo($advertiserId);
                if (! $this->clientAccountInfo) {
                    $err = ['params' => ['token' => '', 'advertiserId' => $advertiserId], 'response' => ['ks client account info is empty！']];
                    $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======');
                    CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, json_encode($err, JSON_UNESCAPED_UNICODE));
                    return;
                }

                $page = 0;
                while (true) {
                    $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
                    if (! $token) {
                        CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, 'token获取失败');
                        break;
                    }
                    ++$page;
                    $result = $this->_getServiceMaterialDailyReport($token, $advertiserId, $startDate, $endDate, $page);
                    if (! $result) {
                        $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'startDate' => $startDate, 'endDate' => $endDate, 'page' => $page], 'response' => FinanceService::getError(0)];
                        $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======');
                        logss($this->getDescription(), $this->getName(), FinanceService::getError(0));
                        CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, json_encode($err, JSON_UNESCAPED_UNICODE));
                        break;
                    }

                    if (isset($result['code']) && $result['code'] != OeCodeEnum::SUCCESS) {
                        $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'startDate' => $startDate, 'endDate' => $endDate, 'page' => $page], 'response' => $result];
                        $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======');
                        logss($this->getDescription(), $this->getName(), $result['message']);
                        CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, json_encode($err, JSON_UNESCAPED_UNICODE));
                        break;
                    }

                    $list = $result['data']['rows'];
                    if (count($list) == 0) {
                        break;
                    }

                    foreach ($list as $v) {
                        $statDate = intval(date('Ymd', strtotime($v['dimensions']['stat_time_day'])));
                        $materialId = $v['dimensions']['material_id'];
                        $materialDailyReportInfo = $this->_getMaterialDailyReportInfo($advertiserId, $statDate, $materialId, $type);

                        if ($materialDailyReportInfo) {
                            if (! $this->_isReportDataUpdate($materialDailyReportInfo, $v)) {
                                $result = $this->_updateMaterialData($materialDailyReportInfo['id'], $v, $type);
                            }
                        } else {
                            $result = $this->_insertMaterialData($advertiserId, $v, $type);
                        }
                    }
                }
            }
        }
        $output->writeln('=======巨量引擎-自定义素材日流水拉取结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    /**
     * 获取账户信息.
     * @param string $advertiserId 账户ID
     * @throws
     */
    private function _getClientAccountInfo(string $advertiserId = ''): array
    {
        $info = (new ClientAccountModel())->where('advertiser_id', $advertiserId)->field(true)->find();

        if (! $info) {
            return [];
        }
        return $info->toArray();
    }

    /**
     * 获取视频信息.
     * @throws
     */
    private function _getOeVideoInfo(string $advertiserId = '', string $materialId = ''): array
    {
        $where = [
            ['advertiser_id', '=', $advertiserId],
            ['material_id', '=', $materialId],
        ];

        $info = (new OeVideoModel())->where($where)->field(true)->find();

        if (! $info) {
            return [];
        }

        return $info->toArray();
    }

    /**
     * 插入广告素材流水信息.
     * @param string $advertiserId 账户ID
     * @param array $info 信息数据
     */
    private function _insertMaterialData(string $advertiserId = '', array $info = [], int $type = 1): bool
    {
        try {
            Db::startTrans();
            $materialId = $info['dimensions']['material_id'];
            $statDate = intval(date('Ymd', strtotime($info['dimensions']['stat_time_day'])));
            $statCost = $info['metrics']['stat_cost'];
            $videoInfo = $this->_getOeVideoInfo($advertiserId, $materialId);

            $signature = '';
            if ($videoInfo) {
                $signature = $videoInfo['signature'];
            }

            $data = [
                'company_id' => $this->clientAccountInfo['company_id'],
                'client_id' => $this->clientAccountInfo['client_id'],
                'account_id' => $this->clientAccountInfo['id'],
                'advertiser_id' => $advertiserId,
                'stat_date' => $statDate,
                'video_id' => $materialId,
                'signature' => $signature,
                'cost' => $statCost,
                'source' => OeMaterialDailyReportModel::SOURCE_CUSTOM,
                'create_time' => time(),
            ];

            if ($type == 1) {
                $insertId = (new OeMaterialDailyReportModel())->insertGetId($data);
            } elseif ($type == 2) {
                $insertId = (new OeMaterialDailyReportHistoryModel())->insertGetId($data);
            }

            if ($insertId <= 0) {
                Db::rollback();
                return false;
            }

            $extData = [
                'company_id' => $this->clientAccountInfo['company_id'],
                'client_id' => $this->clientAccountInfo['client_id'],
                'account_id' => $this->clientAccountInfo['id'],
                'report_id' => $insertId,
                'advertiser_id' => $advertiserId,
                'stat_date' => $statDate,
                'content' => json_encode($info, JSON_UNESCAPED_UNICODE),
                'create_time' => time(),
            ];

            if ($type == 1) {
                $extInsertId = (new OeMaterialDailyReportExtModel())->insertGetId($extData);
            } elseif ($type == 2) {
                $extInsertId = (new OeMaterialDailyReportHistoryExtModel())->insertGetId($extData);
            }

            if ($extInsertId <= 0) {
                Db::rollback();
                return false;
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 判断是否需要更新.
     * @param array $oldData 旧数据
     * @param array $newData 新数据
     */
    private function _isReportDataUpdate(array $oldData = [], array $newData = []): bool
    {
        $one = $oldData['cost'] == $newData['metrics']['stat_cost'];

        if ($one) {
            return true;
        }

        return false;
    }

    /**
     * 修改广告素材流水信息.
     * @param int $id 主键ID
     * @param array $info 信息数据
     */
    private function _updateMaterialData(int $id = 0, array $info = [], int $type = 1): bool
    {
        Db::startTrans();
        $statCost = $info['metrics']['stat_cost'];
        $data = [
            'cost' => $statCost,
            'update_time' => time(),
        ];

        if ($type == 1) {
            $insertId = (new OeMaterialDailyReportModel())->where('id', $id)->update($data);
        } elseif ($type == 2) {
            $insertId = (new OeMaterialDailyReportHistoryModel())->where('id', $id)->update($data);
        }

        if ($insertId <= 0) {
            Db::rollback();
            return false;
        }

        $extData = [
            'content' => json_encode($info, JSON_UNESCAPED_UNICODE),
            'update_time' => time(),
        ];

        if ($type == 1) {
            $extInsertId = (new OeMaterialDailyReportExtModel())->where('report_id', $id)->update($extData);
        } elseif ($type == 2) {
            $extInsertId = (new OeMaterialDailyReportHistoryExtModel())->where('report_id', $id)->update($extData);
        }


        if ($extInsertId <= 0) {
            Db::rollback();
            return false;
        }

        Db::commit();
        return true;
    }

    /**
     * @param string $advertiserId 账户ID
     * @param int $statDate 时间
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function _getMaterialDailyReportInfo(string $advertiserId = '', int $statDate = 0, string $materialId = '', int $type = 1): array
    {
        $where = [
            ['stat_date', '=', $statDate],
            ['advertiser_id', '=', $advertiserId],
            ['video_id', '=', $materialId],
            ['source', '=', OeMaterialDailyReportModel::SOURCE_CUSTOM],
            // ['signature', '=', $signature],
        ];

        $fields = [
            '*',
            "CONCAT(stat_date,'_',advertiser_id,'_',video_id,'_',signature) as k",
        ];

        if ($type == 1) {
            $info = (new OeMaterialDailyReportModel())->where($where)->field($fields)->find();
        } elseif ($type == 2) {
            $info = (new OeMaterialDailyReportHistoryModel())->where($where)->field($fields)->find();
        }

        if (! $info) {
            return [];
        }

        return $info->toArray();
    }

    /**
     * 获取获取广告素材流水信息.
     * @param string $token token
     * @param string $advertiserId 账户ID
     * @param string $startDate 开始时间
     * @param string $endDate 结束 时间
     * @return bool|mixed|string
     */
    private function _getServiceMaterialDailyReport(string $token = '', string $advertiserId = '', string $startDate = '', string $endDate = '', int $page = 1)
    {
        $headers = [
            'Access-Token' => $token,
            // 'Content-Type' => 'application/json',
        ];

        $params = [
            'advertiser_id' => $advertiserId,
            'data_topic' => 'MATERIAL_DATA',
            'metrics' => $this->_getField(),
            'start_time' => $startDate,
            'end_time' => $endDate,
            'page' => $page,
            'page_size' => OceanEnum::MAX_CUSTOM_MATERIAL_PAGE_SIZE,
            'dimensions' => ['image_mode', 'material_id', 'stat_time_day'],
            'filters' => [['field' => 'stat_cost', 'type' => 3, 'operator' => 4, 'values' => ['0' => '0']]],
            'order_by' => [['field' => 'material_id']],
        ];
        return FinanceService::getCustomMaterialDailyReport($headers, $params);
    }

    /**
     * 获取字段列表.
     * @return string[]
     */
    private function _getField(): array
    {
        return [
            'stat_cost',
            'show_cnt',
            'cpm_platform',
            'click_cnt',
            'ctr',
            'cpc_platform',
            'attribution_convert_cnt',
            'attribution_convert_cost',
            'attribution_conversion_rate',
            'attribution_deep_convert_cnt',
            'attribution_deep_convert_cost',
            'attribution_deep_convert_rate',
            'convert_cnt',
            'conversion_cost',
            'conversion_rate',
            'deep_convert_cnt',
            'deep_convert_cost',
            'deep_convert_rate',
            'click_start_cnt',
            'click_start_cost',
            'click_start_rate',
            'download_finish_cnt',
            'download_finish_cost',
            'download_finish_rate',
            'install_finish_cnt',
            'install_finish_cost',
            'install_finish_rate',
            'active',
            'active_cost',
            'active_rate',
            'active_register',
            'active_register_cost',
            'active_register_rate',
            'game_addiction',
            'game_addiction_cost',
            'game_addiction_rate',
            'attribution_next_day_open_cnt',
            'attribution_next_day_open_cost',
            'attribution_next_day_open_rate',
            'next_day_open',
            'active_pay',
            'active_pay_cost',
            'active_pay_rate',
            'game_pay_count',
            'game_pay_cost',
            'attribution_game_pay_7d_count',
            'attribution_game_pay_7d_cost',
            'attribution_active_pay_7d_per_count',
            'in_app_uv',
            'in_app_detail_uv',
            'in_app_cart',
            'in_app_pay',
            'in_app_order',
            'phone',
            'form',
            'form_submit',
            'map',
            'button',
            'view',
            'download_start',
            'qq',
            'lottery',
            'vote',
            'message',
            'redirect',
            'shopping',
            'consult',
            'consult_effective',
            'phone_confirm',
            'phone_connect',
            'phone_effective',
            'coupon',
            'coupon_single_page',
            'redirect_to_shop',
            'poi_address_click',
            'poi_collect',
            'customer_effective',
            'attribution_customer_effective',
            'attribution_customer_effective_cost',
            'attribution_clue_pay_succeed',
            'attribution_clue_pay_succeed_cost',
            'attribution_clue_interflow',
            'attribution_clue_interflow_cost',
            'attribution_clue_high_intention',
            'attribution_clue_high_intention_cost',
            'attribution_game_in_app_ltv_1day',
            'attribution_game_in_app_ltv_2days',
            'attribution_game_in_app_ltv_3days',
            'attribution_game_in_app_ltv_4days',
            'attribution_game_in_app_ltv_5days',
            'attribution_game_in_app_ltv_6days',
            'attribution_game_in_app_ltv_7days',
            'attribution_game_in_app_ltv_8days',
            'attribution_game_in_app_roi_1day',
            'attribution_game_in_app_roi_2days',
            'attribution_game_in_app_roi_3days',
            'attribution_game_in_app_roi_4days',
            'attribution_game_in_app_roi_5days',
            'attribution_game_in_app_roi_6days',
            'attribution_game_in_app_roi_7days',
            'attribution_game_in_app_roi_8days',
            'attribution_day_active_pay_count',
            'attribution_day_active_pay_rate',
            'attribution_day_active_pay_cost',
            'active_pay_intra_day_count',
            'active_pay_intra_day_cost',
            'active_pay_intra_day_rate',
            'loan_completion',
            'loan_completion_cost',
            'loan_completion_rate',
            'pre_loan_credit',
            'pre_loan_credit_cost',
            'loan_credit',
            'loan_credit_cost',
            'loan_credit_rate',
            'total_play',
            'play_duration_3s',
            'valid_play',
            'valid_play_cost',
            'valid_play_rate',
            'valid_play_of_mille',
            'valid_play_cost_of_mille',
            'play_25_feed_break',
            'play_50_feed_break',
            'play_75_feed_break',
            'play_99_feed_break',
            'average_play_time_per_play',
            'play_over_rate',
            'wifi_play_rate',
            'card_show',
            'dy_like',
            'dy_comment',
            'dy_share',
            'dislike_cnt',
            'report_cnt',
            'ies_challenge_click',
            'ies_music_click',
            'location_click',
            'dy_home_visited',
            'dy_follow',
            'message_action',
            'click_landing_page',
            'click_shopwindow',
            'click_website',
            'click_call_dy',
            'click_download',
            'luban_live_enter_cnt',
            'luban_live_follow_cnt',
            'luban_live_share_cnt',
            'luban_live_comment_cnt',
            // 'pv',
            // 'uv',
            // 'avg_load_duration',
            // 'bounced_count',
            // 'bounced_rate',
            // 'lt_3s_bounced_count',
            // 'lt_3s_bounced_rate',
            // 'ge_3s_stay_count',
            // 'ge_3s_stay_rate',
            // 'ge_3s_stay_cvr',
            // 'avg_scroll_ratio',
            // 'avg_scroll_count',
            // 'avg_stay_duration',
            'click_call_cnt',
            'click_counsel',
            'form_click_button',
            'coupon_addition',
        ];
    }
}
